package com.xzy.learn.spring.bean.definition;

import com.xzy.learn.spring.entity.User;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * {@link org.springframework.beans.factory.config.BeanDefinition} 注册示例
 *
 * @author xzy.xiao
 * @date 2022/5/30  16:40
 */
public class BeanDefinitionRegistrationDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        AbstractBeanDefinition beanDefinition = BeanDefinitionCreationDemo.buildBeanDefinitionByBeanDefinitionBuilder();

        registerBeanDefinition(applicationContext, "myGivenName", beanDefinition);
        registerBeanDefinition(applicationContext, "", beanDefinition);

        applicationContext.refresh();
        Map<String, User> beans = applicationContext.getBeansOfType(User.class);
        System.out.println(beans);

    }

    public static void registerBeanDefinition(BeanDefinitionRegistry beanDefinitionRegistry, @Nullable String beanName, AbstractBeanDefinition abstractBeanDefinition) {
        if (StringUtils.hasText(beanName)) {
            // A.由使用者指定 Bean 的名称
            beanDefinitionRegistry.registerBeanDefinition(beanName, abstractBeanDefinition);
        } else {
            // B.由系统自动生成 Bean 的名称
            BeanDefinitionReaderUtils.registerWithGeneratedName(abstractBeanDefinition, beanDefinitionRegistry);
        }
    }
}
